package com.atguigu.tingshu.user.startagy.impl;

import cn.hutool.core.date.DateUtil;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.model.user.UserVipService;
import com.atguigu.tingshu.model.user.VipServiceConfig;
import com.atguigu.tingshu.user.mapper.UserInfoMapper;
import com.atguigu.tingshu.user.mapper.UserVipServiceMapper;
import com.atguigu.tingshu.user.service.VipServiceConfigService;
import com.atguigu.tingshu.user.startagy.ItemTypeStrategy;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

@Component("1003")
@Slf4j
public class VipStrategy implements ItemTypeStrategy {

    @Autowired
    private UserVipServiceMapper userVipServiceMapper;

    @Autowired
    private VipServiceConfigService vipServiceConfigService;

    @Autowired
    private UserInfoMapper userInfoMapper;


    @Override
    public void savePaidRecord(UserPaidRecordVo userPaidRecordVo) {
        log.info("VIP策略模式执行。。。");
        List<Long> itemIdList = userPaidRecordVo.getItemIdList();
        Long userId = userPaidRecordVo.getUserId();
        String orderNo = userPaidRecordVo.getOrderNo();
        Long count = userVipServiceMapper.selectCount(new LambdaQueryWrapper<UserVipService>().eq(UserVipService::getOrderNo, orderNo));
        if(count > 0){
            return;
        }
        //vip
        if(!CollectionUtils.isEmpty(itemIdList)){
            Long vipId = itemIdList.get(0);
            UserVipService userVipService = new UserVipService();
            userVipService.setOrderNo(orderNo);
            userVipService.setUserId(userId);
            UserInfo userInfo = userInfoMapper.selectById(userId);
            VipServiceConfig vipServiceConfig = vipServiceConfigService.getById(vipId);
            Date expireTime;
            if(userInfo.getIsVip().intValue() == 1 && userInfo.getVipExpireTime().after(new Date())){
                expireTime = userInfo.getVipExpireTime();
            }else{
                expireTime = new Date();
            }
            userVipService.setStartTime(expireTime);
            userVipService.setExpireTime(DateUtil.offsetMonth(expireTime,vipServiceConfig.getServiceMonth()));
            userVipService.setNextRenewTime(DateUtil.offsetMonth(expireTime,vipServiceConfig.getServiceMonth()));
            userVipService.setIsAutoRenew(0);

            userVipServiceMapper.insert(userVipService);
            //更新用户表
            userInfo.setIsVip(1);
            userInfo.setVipExpireTime(userVipService.getExpireTime());
            userInfoMapper.updateById(userInfo);
        }
    }
}
